<template>
  <div class="app-container">
    <!-- <div class="filter-container">
      <el-button size="small" class="filter-item" type="primary" @click="handleFilter">查询</el-button>
      <el-button size="small" class="filter-item" type="danger" icon="el-icon-refresh" @click="handleUpdateVersion">版本更新</el-button>
    </div> -->
    <div class="filter-container">
      <el-input
        size="small"
        v-model="listQuery.title"
        style="width: 300px"
        class="filter-item"
        placeholder="名称"
        clearable
      />
      <el-button
        size="small"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        查询
      </el-button>
      <el-button
        size="small"
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="edit"
        @click="showCreate"
      >
        添加
      </el-button>
    </div>
    <div class="table-container">
      <el-table
        key="tableList"
        v-loading="listLoading"
        :data="list"
        element-loading-text="加载中"
        border
        fit
        stripe
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column align="center" label="编号" width="80">
          <template slot-scope="scope">
            {{ scope.row.id }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="模块"
          class-name="overflow-on"
          width="100px"
        >
          <template slot-scope="scope">
            {{ scope.row.type }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="标题"
          class-name="overflow-on"
          width="350px"
        >
          <template slot-scope="scope">
            {{ scope.row.title }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="显示时间"
          class-name="overflow-on"
        >
          <template slot-scope="scope">
            {{ scope.row.startTime }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="资讯内容"
          class-name="overflow-on"
          width="250px"
        >
          <template slot-scope="scope">
            {{ scope.row.introduction }}
          </template>
        </el-table-column>

        <!-- <el-table-column align="center" label="封面图" width="100">
          <template slot-scope="scope">
            <el-image style="width: 60px;" :src="scope.row.cover" :preview-src-list="scope.row.imglist"></el-image>
          </template>
        </el-table-column> -->
        <el-table-column align="center" label="是否置顶">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.top"
              active-color="#13ce66"
              :inactive-value="0"
              :active-value="1"
              inactive-color="grey"
              @change="changeTopStatus(scope.row, scope.row.top)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column align="center" label="更新时间">
          <template slot-scope="scope">
            <span>{{ scope.row.updated_at }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="发布状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status ? 'success' : 'warning'">
              <span>{{ scope.row.status == 1 ? "已显示" : "已屏蔽" }}</span>
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" width="250">
          <template slot-scope="scope">
            <el-button
              plain
              type="primary"
              size="small"
              @click="updateAction(scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              plain
              v-if="scope.row.status == 1"
              size="small"
              type="warning"
              @click="changeStatus(scope.row, 0)"
              >去停用</el-button
            >
            <el-button
              plain
              v-else
              size="small"
              type="success"
              @click="changeStatus(scope.row, 1)"
              >去发布</el-button
            >
            <el-button
              plain
              size="small"
              type="danger"
              @click="handleDel(scope.row)"
              >删除</el-button
            >
            <!-- <el-button plain type="success" size="small" @click="openUrlAction(scope.row)" > 查看 </el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination-container text-right">
      <el-pagination
        background
        :total="pagination.total"
        :current-page="listQuery.page"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
      <el-form
        ref="temp"
        class="small-space"
        :model="temp"
        :rules="rules"
        label-position="right"
        label-width="100px"
      >
        <el-form-item label="类型" prop="type" required>
          <el-select
            size="small"
            v-model="temp.type"
            default-first-option
            placeholder="类型"
            clearable
            class="filter-item"
            disabled
          >
            <el-option
              v-for="(item, index) in typeList"
              :key="index"
              :label="item"
              :value="index"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="标题" prop="title" required>
          <el-input size="small" v-model="temp.title" />
        </el-form-item>

        <el-form-item label="来源">
          <el-input size="small" v-model="temp.origin" />
        </el-form-item>
        <!-- <el-form-item label="封面">
          <el-upload class="avatar-uploader" :action="uploadPath" :headers="header"
            :show-file-list="false" :on-success="handleImageSuccess">
            <img v-if="temp.cover" :src="temp.cover" style="width: 200px" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item> -->

        <el-form-item label="显示日期" required prop="startTime">
          <el-date-picker
            v-model="temp.startTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="发布状态" prop="status" required>
          <el-radio-group v-model="temp.status">
            <el-radio :label="1">发布</el-radio>
            <el-radio :label="0">不发布</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="主体内容" prop="content" required>
          <div style="border: 1px solid #ccc;">
            <Toolbar
              :editor="editor"
              :defaultConfig="toolbarConfig"
              :mode="mode"
              style="border-bottom: 1px solid #ccc"
            />
            <Editor
              v-model="temp.content"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="onCreated"
              style="height: 500px; overflow-y: hidden;"
            />
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer text-right">
        <el-button @click="dialogFormVisible = false"> 取 消 </el-button>
        <el-button type="primary" :disabled="btn" @click="handleSave('temp')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getList,
  create,
  info,
  edit,
  Status,
  topStatus,
  Del
} from "@/api/news";
import { getToken } from "@/utils/auth";
import { uploadPath } from "@/utils/common";
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

export default {
  components: { Editor, Toolbar },
  data() {
    return {
      editor: null,
      toolbarConfig: {},
      editorConfig: {
        placeholder: "请输入内容...",
        MENU_CONF: {}
      },
      mode: "default", // or 'simple'
      btn: false,
      list: null,
      typeList: [],
      uploadPath: uploadPath,
      rules: {
        title: [{ required: true, message: "请输入标题！", trigger: "blur" }],
        content: [{ type: "string", required: true, message: "请输入内容" }],
        startTime: [
          { required: true, message: "请选择时间！", trigger: "blur" }
        ]
      },
      pagination: {},
      listLoading: false,
      dialogFormVisible: false,
      temp: {},
      listQuery: {
        page: 1,
        limit: 10,
        type: "培训资讯"
      },
      dialogTitle: "添加",
      header: {
        Authorization: getToken()
      },
      value: "100",
      status: 1,
      content: null,
      origin: null
    };
  },
  created() {
    this.getList();
    this.editorConfig.MENU_CONF["uploadImage"] = {
      server: uploadPath,
      fieldName: "file",
      // 单个文件的最大体积限制，默认为 2M
      maxFileSize: 2 * 1024 * 1024, // 2M
      // 最多可上传几个文件，默认为 100
      maxNumberOfFiles: 10,
      // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
      allowedFileTypes: ["image/*"],
      // 自定义增加 http  header
      headers: {
        Authorization: getToken()
      },
      // 跨域是否传递 cookie ，默认为 false
      withCredentials: false,
      // 超时时间，默认为 10 秒
      timeout: 5 * 1000, // 5 秒
      // 自定义插入图片
      customInsert(res, insertFn) {
        // res 即服务端的返回结果
        // 从 res 中找到 url alt href ，然后插图图片
        console.log(res.data.filepath);
        insertFn(res.data.filepath, "", "");
      }
    };
    this.toolbarConfig = {
      excludeKeys: ["insertVideo", "uploadVideo", "group-video"]
    };
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
    },
    getList() {
      this.listLoading = true;
      getList(this.listQuery).then(response => {
        //this.typeList = response.data.typeList

        var data = response.data;
        this.list = data.data;
        this.pagination = data;
        //console.log(this.list)
        //图片放大处理，声明一个数组，遍历一遍
        this.list.forEach(e => {
          e.imglist = [];
          e.imglist.push(e.cover);
        });
      });
      this.listLoading = false;
    },

    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },

    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },

    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },

    changeStatus(row, status) {
      Status({ id: row.id, status: status, type: this.listQuery.type }).then(
        response => {
          row.status = status;
          this.$message.success(response.msg);
          this.getList();
        }
      );
    },

    changeTopStatus(row, top) {
      const _this = this;

      topStatus({ id: row.id, top: top, type: this.listQuery.type }).then(
        response => {
          row.top = top;

          this.$message.success(response.msg);
          this.getList();
        }
      );
    },

    handleImageSuccess(res, file) {
      if (res.code === 0) {
        this.temp.cover = res.data.filepath;
        //图片相对路径处理
        //this.temp.image_path=process.env.VUE_APP_BASE_PIC +  this.temp.image_path
        this.temp.cover = this.temp.cover;
        // uploadPath = uploadPath.this.temp.image_path;

        this.$message.success("上传成功！");
      } else {
        this.$message.error(res.msg);
      }
    },

    // handleUpdateVersion() {
    //   this.$confirm('谨慎操作！！！***，确认要更新嘛?', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning',
    //   }).then(() => {
    //     updateVersion().then((res) => {
    //       if (res.code === 0) {
    //         this.$message.success('版本更新成功！')
    //         this.getList()
    //       } else {
    //         this.$message.error(res.data.msg)
    //       }
    //     })
    //   })
    // },

    // openUrlAction(val){
    //   if(val.type == 0){
    //     // 默认
    //     let routeUrl = '/protocol?id=' + val.id;
    //     window.open(routeUrl, '_blank')
    //   }else if(val.type == 1){
    //     //隐私
    //     let routeUrl = '/protocol/privacy?body=' + val.main_body;
    //     window.open(routeUrl, '_blank')
    //   }else if(val.type == 2){
    //     //用户
    //     let routeUrl = '/protocol/user?body=' + val.main_body;
    //     window.open(routeUrl, '_blank')
    //   }else{
    //     let routeUrl = '/protocol/child?body=' + val.main_body;
    //     window.open(routeUrl, '_blank')
    //   }
    // },

    doAdd() {
      create(this.temp).then(res => {
        if (res.code === 0) {
          this.$message.success("添加成功！");
          this.getList();
          this.dialogFormVisible = !this.dialogFormVisible;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    handleSave(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // this.btn = true;
          if (this.dialogTitle === "添加") {
            this.doAdd();
          } else {
            edit(this.temp).then(res => {
              this.btn = false;
              if (res.code === 0) {
                this.$message.success(res.msg);
                this.getList();
                this.dialogFormVisible = !this.dialogFormVisible;
              } else {
                this.$message.error(res.msg);
              }
            });
          }
        } else {
          this.$notify.error({
            title: "错误",
            message: "请检查输入是否正确",
            offset: 100
          });
          return false;
        }
      });
    },

    updateAction(id) {
      info({ id: id }).then(res => {
        if (res.code === 0) {
          this.btn = false;
          this.temp = res.data;
          this.dialogTitle = "编辑";
          this.dialogFormVisible = !this.dialogFormVisible;
        } else {
          this.$message.error(res.msg);
        }
      });
    },

    showCreate() {
      this.temp = {
        title: null,
        cover: "",
        origin: "",
        cover: "",
        type: this.listQuery.type,
        startTime: "",
        status: 0
      };
      this.btn = false;
      this.dialogTitle = "添加";
      this.dialogFormVisible = !this.dialogFormVisible;
    },
    handleDel(row) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          console.log(row.id);
          Del({ id: row.id, type: this.listQuery.type }).then(response => {
            if (response.code === 0) {
              this.$message({
                message: response.msg,
                type: "success"
              });
              this.dialogFormVisible = false;
              this.getList();
            } else {
              this.$message({
                message: response.msg,
                type: "error"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }
    // handleImageSuccess(res, file) {
    //   if (res.code === 0) {
    //     this.temp.cover =res.data.filepath;
    //     //图片相对路径处理
    //    //this.temp.image_path=process.env.VUE_APP_BASE_PIC +  this.temp.image_path
    //    this.temp.cover=this.temp.cover
    //    // uploadPath = uploadPath.this.temp.image_path;

    //     this.$message.success('上传成功！')
    //   } else {
    //     this.$message.error(res.msg)
    //   }
    // },
  }
};
</script>

<style>
.overflow-on .cell {
  overflow: visible;
  overflow-x: visible;
  overflow-y: visible;
}
/* .table-container {
  margin: 20px 0;
} */
.ql-editor {
  height: 360px;
}
</style>
